import { useEffect, useRef, useState } from 'react';
import styles from './banner.less';
import _ from 'lodash';

const Banner = () => {
  const banner = useRef<any>(null);
  const [current, setCurrent] = useState<number>(0);
  useEffect(() => {
    const Banner = banner.current;
    const list_a = Banner.querySelectorAll('a');
    setDOMStyle(0, list_a, 0);
  }, []);
  useEffect(() => {
    const Banner = banner.current;
    const list_a = Banner.querySelectorAll('a');
    const timeOut = setTimeout(() => {
      if (current + 1 >= list_a.length) {
        setCurrent(0);
        setDOMStyle(0, list_a, list_a.length - 1);
      } else {
        setCurrent(current + 1);
        setDOMStyle(current + 1, list_a, current);
      }
    }, 3000);
    return () => {
      clearTimeout(timeOut);
    };
  }, [current]);

  const setDOMStyle: (current: any, list: any[], oldCurrent: number) => void = (
    current,
    list,
    oldCurrent,
  ) => {
    if (oldCurrent === 0 || oldCurrent) {
      list[oldCurrent].style.display = 'none';
      let opacity = 50;
      let speed = 1;
      const end_opacity = 0;
      const interOut = setInterval(() => {
        opacity -= speed;

        list[oldCurrent].style.opacity = opacity / 100;
        if (opacity <= end_opacity) {
          clearInterval(interOut);
        }
      }, 1);
    }
    list[current].style.display = 'block';
    let opacity = 50;
    let speed = 1;
    const end_opacity = 100;
    const interOut = setInterval(() => {
      opacity += speed;
      list[current].style.opacity = opacity / 100;

      if (opacity >= end_opacity) {
        clearInterval(interOut);
      }
    }, 1);
  };

  return (
    <div className={styles.banner} ref={banner}>
      <a
        style={{
          background:
            'url(//image4.benlailife.com/sjss0222.jpg) 50% 0% no-repeat',
        }}
      ></a>
      <a
        style={{
          background:
            'url("//image4.benlailife.com/sjbgsz0222.jpg") 50% 0% no-repeat',
        }}
      ></a>
      <a
        style={{
          background:
            'url("//image4.benlailife.com/sjzcwd0222.jpg") 50% 0% no-repeat',
        }}
      ></a>
      <a
        style={{
          background:
            'url("//image4.benlailife.com/sjqwcj0217.jpg") 50% 0% no-repeat',
        }}
      ></a>
      <a
        style={{
          background:
            'url("//image4.benlailife.com/sjhgg0222.jpg") 50% 0% no-repeat',
        }}
      ></a>
      <a
        style={{
          background:
            'url("//image4.benlailife.com/sjhg0210.jpg") 50% 0% no-repeat',
        }}
      ></a>
    </div>
  );
};

export default Banner;
